import React, { useState } from 'react';
import {
  Box,
  Button,
  FormControl,
  Input,
  VStack,
  Heading,
  Text,
  useToast,
  Radio,
  RadioGroup,
  Stack,
  List,
  ListItem,
  Divider,
  HStack,
  Badge,
  Select,
  FormLabel,
  Collapse,
} from '@chakra-ui/react';
import { SearchIcon } from '@chakra-ui/icons';
import { searchMethods } from '../api/api';

const MethodSearch = ({ onMethodSelect }) => {
  const [methodName, setMethodName] = useState('');
  const [queryType, setQueryType] = useState('self');
  const [pathDepth, setPathDepth] = useState('1');
  const [searchResults, setSearchResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const toast = useToast();

  const handleSearch = async () => {
    if (!methodName.trim()) {
      toast({
        title: '请输入方法名',
        status: 'warning',
        duration: 3000,
        isClosable: true,
      });
      return;
    }

    setLoading(true);

    try {
      const response = await searchMethods(methodName);
      setSearchResults(response.data || []);
      
      if (response.data.length === 0) {
        toast({
          title: '未找到结果',
          description: `未找到名称包含 "${methodName}" 的方法`,
          status: 'info',
          duration: 3000,
          isClosable: true,
        });
      }
    } catch (error) {
      toast({
        title: '搜索失败',
        description: error.message || '无法执行搜索',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSelectMethod = (method) => {
    console.log("选择方法:", method);
    onMethodSelect({
      fullName: method.full_name,
      nodeId: method.node_id, // 传递节点ID
      queryType,
      pathDepth: parseInt(pathDepth, 10),
    });
  };

  return (
    <Box p={5} shadow="md" borderWidth="1px" borderRadius="md" bg="white" width="100%">
      <Heading size="md" mb={4}>搜索方法</Heading>
      
      <VStack spacing={4} align="stretch">
        <FormControl>
          <Input
            placeholder="输入方法名称，如: com.webank.deposit.ba.service"
            value={methodName}
            onChange={(e) => setMethodName(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            size="lg"
            fontSize="md"
            py={6}
            width="100%"
            name="methodName"
            autoComplete="on"
          />
        </FormControl>
        
        <HStack>
          <Button
            leftIcon={<SearchIcon />}
            colorScheme="blue"
            isLoading={loading}
            onClick={handleSearch}
            size="lg"
            width="100%"
          >
            搜索
          </Button>
        </HStack>
        
        <RadioGroup onChange={setQueryType} value={queryType}>
          <Text fontWeight="bold" mb={2}>查询类型:</Text>
          <Stack direction="row" spacing={6} justify="center">
            <Radio value="self" size="lg">当前节点</Radio>
            <Radio value="upstream" size="lg">上游节点</Radio>
            <Radio value="downstream" size="lg">下游树</Radio>
          </Stack>
        </RadioGroup>
        
        {/* 路径深度选择，在选择上游节点或下游树时显示 */}
        <Collapse in={queryType === 'downstream' || queryType === 'upstream'} animateOpacity>
          <Box p={3} borderWidth="1px" borderRadius="md" borderStyle="dashed" mt={2}>
            <FormControl>
              <FormLabel fontWeight="semibold">路径深度:</FormLabel>
              <Select 
                value={pathDepth} 
                onChange={(e) => setPathDepth(e.target.value)}
                size="md"
              >
                <option value="1">1级（直接关联）</option>
                <option value="2">2级（包含关联节点的关联节点）</option>
                <option value="3">3级</option>
                <option value="5">5级</option>
                <option value="10">10级</option>
                <option value="-1">全部（所有可达节点）</option>
              </Select>
              <Text fontSize="xs" color="gray.500" mt={1}>
                注意：深度越大，查询耗时越长，图形越复杂
              </Text>
            </FormControl>
          </Box>
        </Collapse>
        
        {searchResults.length > 0 && (
          <Box mt={4}>
            <Divider my={2} />
            <Text fontWeight="bold" mb={2}>搜索结果: {searchResults.length} 条</Text>
            
            <List spacing={2}>
              {searchResults.map((method, index) => (
                <ListItem key={`${method.node_id || method.full_name}-${index}`} p={3} borderWidth="1px" borderRadius="md" _hover={{ bg: "gray.50" }}>
                  <Box onClick={() => handleSelectMethod(method)} cursor="pointer">
                    <Text fontWeight="bold">{method.name}</Text>
                    <Text fontSize="sm" color="gray.600">{method.full_name}</Text>
                    {method.node_id && (
                      <Text fontSize="xs" color="gray.400" mt={1}>ID: {method.node_id}</Text>
                    )}
                    <HStack mt={1}>
                      {method.is_static && <Badge colorScheme="purple">静态</Badge>}
                      {method.is_constructor && <Badge colorScheme="green">构造函数</Badge>}
                      <Badge colorScheme="blue">{method.visibility || 'public'}</Badge>
                    </HStack>
                  </Box>
                </ListItem>
              ))}
            </List>
          </Box>
        )}
      </VStack>
    </Box>
  );
};

export default MethodSearch; 